package com.message.Aliyun_ai_API.service.impl;

import com.base.helper.Result;
import com.message.Aliyun_ai_API.Enum.TextFont;
import com.message.Aliyun_ai_API.Enum.TexttoImageStyle;
import com.message.Aliyun_ai_API.Enum.Texture_style;
import com.message.Aliyun_ai_API.service.WanXPictureService;
import com.message.Aliyun_ai_API.util.Aliyun_ai_imageUtil;
import com.message.Baidu_ai_API.util.FileUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.web.client.HttpClientErrorException;
import org.springframework.web.client.HttpServerErrorException;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class WanXPictureServiceImpl implements WanXPictureService {

    @Value("${external.resource.dir}")
    private String externalResourceDir;
    private final RestTemplate restTemplate;//发http的
    @Value("${service.api_service.api_key}")
    private String API_KEY; //API密钥
    public WanXPictureServiceImpl(RestTemplate restTemplate) {
        this.restTemplate = restTemplate;
    }
    @Override
    public Map TextToImage(Integer id,String prompt,Integer options,int amount) throws Exception {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);//固定，返回类型，只有json
        headers.set("Authorization", API_KEY);//固定，api密钥
        headers.set("X-DashScope-Async", "enable");//只有默认，异步提交任务
       String url="https://dashscope.aliyuncs.com/api/v1/services/aigc/text2image/image-synthesis";//文生图url
        Map<String, Object> input = new HashMap<>();//放到request中
        input.put("prompt", prompt);//////////文本描述
        input.put("size", 1024*1024);//////////尺寸
        Map<String, Object> parameters = new HashMap<>();//放到request中
        parameters.put("style", TexttoImageStyle.fromStyleCode(options).getStyleName());//////////类型
        parameters.put("n", amount);//////////数量
        Map<String, Object> request = new HashMap<>();//请求体
        request.put("model", "wanx-v1");/////////选择模型wanx-v1，一个apikey可以冲所有模型，详情看文档介绍
        request.put("input", input);/////////文本描述和尺寸
        request.put("parameters", parameters);//////////类型和数量
        HttpEntity<Map<String, Object>> entity = new HttpEntity<>(request, headers);//生成一个请求内容
        ResponseEntity<Map> response = restTemplate.postForEntity(url, entity, Map.class);//发送
        return (Map)response.getBody().get("output");
    }
    @Override
    public String getTextToImage(Integer id,String taskId) throws Exception{
                String Url="RUNING";
                HttpHeaders h = new HttpHeaders();
                h.set("Authorization", API_KEY);

                HttpEntity<Void> requestGetFromTask = new HttpEntity<>(h);
                ResponseEntity<Map> responseGetFromTask= restTemplate.exchange(
                        "https://dashscope.aliyuncs.com/api/v1/tasks/{taskId}",
                        HttpMethod.GET,
                        requestGetFromTask,
                        Map.class,
                        taskId
                );
                Map NewResponse = responseGetFromTask.getBody();
                if ("SUCCEEDED".equals(((Map) NewResponse.get("output")).get("task_status"))) {//检查任务状态
                    List<Map<String, String>> results=(List<Map<String, String>>) ((Map) NewResponse.get("output")).get("results");
                    String NewUrl=results.get(0).get("url");//获取返回的阿里云云上的图片url
                    String myUrl=externalResourceDir+"/"+id+taskId+".png";//创建路径
                    Aliyun_ai_imageUtil.downloadImage(NewUrl,myUrl,id,taskId);//下载图片
                    Url= Aliyun_ai_imageUtil.getImageOfUrl(myUrl,externalResourceDir);//映射url
                }
            return Url;
    }

    @Override
    public Map AiTryon(Integer id, String top_garment_url, String bottom_garment_url, String person_image_url,String top_garmentName,String bottom_garmentName,String person_imageName) throws Exception {
        // 设置HTTP头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.set("Authorization", "Bearer " + API_KEY); // 注意这里应该是Bearer token格式
        headers.set("X-DashScope-Async", "enable");

        // 构建请求体
        Map<String, Object> input = new HashMap<>();
        input.put("top_garment_url", top_garment_url);//"https://img.alicdn.com/i4/2212857581220/O1CN01e99nwg1KsnzTIY2VG_!!2212857581220.jpg"测试用图
        input.put("bottom_garment_url",bottom_garment_url);//"https://cbu01.alicdn.com/img/ibank/O1CN01E0ff2V1ScKihhYUAL_!!2214053772267-0-cib.jpg"测试用图
        input.put("person_image_url", person_image_url);//"https://c-ssl.duitang.com/uploads/item/201410/23/20141023222303_4UYNu.jpeg"测试用图


        Map<String, Object> parameters = new HashMap<>();
        parameters.put("resolution", -1); // 确认这是API接受的有效值
        parameters.put("restore_face", true);

        Map<String, Object> request = new HashMap<>();
        request.put("model", "aitryon");
        request.put("input", input);
        request.put("parameters", parameters);
        String url = "https://dashscope.aliyuncs.com/api/v1/services/aigc/image2image/image-synthesis/";

        HttpEntity<Map<String, Object>> entity = new HttpEntity<>(request, headers);

        try {
            ResponseEntity<Map> response = restTemplate.postForEntity(url, entity, Map.class);

            // 检查响应状态码是否为200 OK
            if (response.getStatusCode() == HttpStatus.OK) {
                return (Map)response.getBody().get("output");
            } else {
                throw new RuntimeException("无法获取返回: " + response.getStatusCode());
            }
        } catch (HttpClientErrorException e) {
            System.err.println(e.getResponseBodyAsString());
            throw e;
        } catch (HttpServerErrorException e) {
            System.err.println(e.getResponseBodyAsString());
            throw e;
        }
    }
    @Override
    public String getAiTryon(Integer id,String taskId,String top_garmentName,String bottom_garmentName,String person_imageName) throws Exception {
             String Url="RUNNING";
                HttpHeaders h = new HttpHeaders();
                h.set("Authorization", API_KEY);

                HttpEntity<Void> requestGetFromTask = new HttpEntity<>(h);
                ResponseEntity<Map> responseGetFromTask= restTemplate.exchange(
                        "https://dashscope.aliyuncs.com/api/v1/tasks/{taskId}",
                        HttpMethod.GET,
                        requestGetFromTask,
                        Map.class,
                        taskId
                );
                Map NewResponse = responseGetFromTask.getBody();
                if ("SUCCEEDED".equals(((Map) NewResponse.get("output")).get("task_status"))) {//检查任务状态
                   String url=(String) ((Map) NewResponse.get("output")).get("image_url");
                    String myUrl=externalResourceDir+"/"+id+taskId+".png";//创建路径
                    Aliyun_ai_imageUtil.downloadImage(url,myUrl,id,taskId);//下载图片
                    Url= Aliyun_ai_imageUtil.getImageOfUrl(myUrl,externalResourceDir);//映射url
                    // 删除指定文件
                    FileUtil.deleteFileIfExists(externalResourceDir, top_garmentName);
                    FileUtil.deleteFileIfExists(externalResourceDir, bottom_garmentName);
                    FileUtil.deleteFileIfExists(externalResourceDir, person_imageName);
                }
            return Url;
    }
    @Override
    public Map generation(Integer id,String image_Url,Integer style_index,MultipartFile style_ref_url) throws Exception {
        // 设置HTTP头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);//固定，返回类型，只有json
        headers.set("Authorization", API_KEY);//固定，api密钥
        headers.set("X-DashScope-Async", "enable");//只有默认，异步提交任务
        String url="https://dashscope.aliyuncs.com/api/v1/services/aigc/image-generation/generation";//风格转换url
        Map<String, Object> input = new HashMap<>();//放到request中
        input.put("image_url", image_Url);//////////图片url
        // "https://c-ssl.duitang.com/uploads/item/201410/23/20141023222303_4UYNu.jpeg"测试用图
        input.put("style_index", style_index);//////////样式
        Map<String, Object> request = new HashMap<>();//请求体
        request.put("model", "wanx-style-repaint-v1");/////////选择模型wanx-style-repaint-v1，一个apikey可以冲所有模型，详情看文档介绍
        request.put("input", input);/////////文本描述和尺寸
        HttpEntity<Map<String, Object>> entity = new HttpEntity<>(request, headers);//生成一个请求内容
        ResponseEntity<Map> response = restTemplate.postForEntity(url, entity, Map.class);//发送
        return (Map)response.getBody();
    }
    @Override
    public String getgeneration(Integer id,String taskId,String image_Name) throws Exception {
        String Url="RUNNING";
        HttpHeaders h = new HttpHeaders();
        h.set("Authorization", API_KEY);

        HttpEntity<Void> requestGetFromTask = new HttpEntity<>(h);
        ResponseEntity<Map> responseGetFromTask= restTemplate.exchange(
                "https://dashscope.aliyuncs.com/api/v1/tasks/{taskId}",
                HttpMethod.GET,
                requestGetFromTask,
                Map.class,
                taskId
        );
        Map NewResponse = responseGetFromTask.getBody();
        if ("SUCCEEDED".equals(((Map) NewResponse.get("output")).get("task_status"))) {//检查任务状态
            ArrayList<Map<String,String>> list=(ArrayList<Map<String,String>>) ((Map) NewResponse.get("output")).get("results");
            String url=list.get(0).get("url");
            String myUrl=externalResourceDir+"/"+id+taskId+".png";//创建路径
            Aliyun_ai_imageUtil.downloadImage(url,myUrl,id,taskId);//下载图片
            Url= Aliyun_ai_imageUtil.getImageOfUrl(myUrl,externalResourceDir);//映射url
            // 删除指定文件
            FileUtil.deleteFileIfExists(externalResourceDir, image_Name);
        }
        return Url;
    }
    @Override
    public Map texture(Integer userid,String text_content,String output_image_ratio,Integer font_name,String prompt,Integer texture_style) throws Exception {
        // 设置HTTP头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);//固定，返回类型，只有json
        headers.set("Authorization", API_KEY);//固定，api密钥
        headers.set("X-DashScope-Async", "enable");//只有默认，异步提交任务
        String url="https://dashscope.aliyuncs.com/api/v1/services/aigc/wordart/texture";//风格转换url
        Map<String, Object> text=new HashMap<>();/////////////////input中的text对象
        text.put("text_content",text_content);//设置文字内容
        text.put("font_name", TextFont.fromStyleCode(font_name));//设置文字样式
        text.put("output_image_ratio",output_image_ratio);//设置图片中文字比例
        Map<String, Object> input = new HashMap<>();//放到request中
        input.put("text", text);//////////将text对象放进来
        input.put("prompt", prompt);//////////提示词
        input.put("texture_style", Texture_style.fromStyleCode(texture_style));//////////样式
        Map<String,Object> parameters=new HashMap<>();
        parameters.put("image_short_size",704);//默认尺寸
        parameters.put("n",1);//默认一张
        parameters.put("alpha_channel",false);//默认不带alpha通道
        Map<String, Object> request = new HashMap<>();//请求体
        request.put("model", "wordart-texture");/////////选择模型wordart-texture，一个apikey可以冲所有模型，详情看文档介绍
        request.put("input", input);/////////input放进来
        request.put("parameters", parameters);/////////parameters对象
        HttpEntity<Map<String, Object>> entity = new HttpEntity<>(request, headers);//生成一个请求内容
        ResponseEntity<Map> response = restTemplate.postForEntity(url, entity, Map.class);//发送
        return (Map)response.getBody();
    }
    @Override
    public String getTexture(Integer id,String taskId) throws Exception {
        String Url="RUNNING";
        HttpHeaders h = new HttpHeaders();
        h.set("Authorization", API_KEY);

        HttpEntity<Void> requestGetFromTask = new HttpEntity<>(h);
        ResponseEntity<Map> responseGetFromTask= restTemplate.exchange(
                "https://dashscope.aliyuncs.com/api/v1/tasks/{taskId}",
                HttpMethod.GET,
                requestGetFromTask,
                Map.class,
                taskId
        );
        Map NewResponse = responseGetFromTask.getBody();
        if ("SUCCEEDED".equals(((Map) NewResponse.get("output")).get("task_status"))) {//检查任务状态
            ArrayList<Map<String,String>> list=(ArrayList<Map<String,String>>) ((Map) NewResponse.get("output")).get("results");
            String url=list.get(0).get("url");
            String myUrl=externalResourceDir+"/"+id+taskId+".png";//创建路径
            Aliyun_ai_imageUtil.downloadImage(url,myUrl,id,taskId);//下载图片
            Url= Aliyun_ai_imageUtil.getImageOfUrl(myUrl,externalResourceDir);//映射url
            System.out.println(Url);
        }
        return Url;
    }
}
